package com.jake.spring.mvc.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class HttpClientUtils {

    public static String post(String url, Map<String, String> requestMap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String requestString = JSON.toJSONString(requestMap);
        StringEntity stringEntity = new StringEntity(requestString, Charsets.UTF_8);
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            log.error("POST请求出错", e);
        }
        return null;
    }

}
